<template>
  <div class="hotel-search">
    <!-- 左右两列布局 -->
    <div class="search-layout">
      <!-- 左侧：查询和筛选区域 -->
      <div class="left-sidebar">
        <!-- 标题 -->
        <div class="sidebar-header">
          <h2>酒店搜索</h2>
        </div>
        
        <!-- 左侧内容滚动区域 -->
        <div class="sidebar-content">
          <!-- 查询条件 -->
          <el-card class="query-card">
          <template #header>
            <h3>查询条件</h3>
          </template>
          
          <el-form :model="searchForm" @submit.prevent="searchHotels" label-position="top">
            <el-form-item label="目的地城市">
              <el-select 
                v-model="searchForm.cityCode" 
                placeholder="选择城市"
                filterable
                clearable
                :loading="cityLoading"
                @change="handleCityChange"
                style="width: 100%"
              >
                <el-option
                  v-for="city in cityList"
                  :key="city.cityCode"
                  :label="city.cityName"
                  :value="city.cityCode"
                >
                  <span>{{ city.cityName }}</span>
                  <span style="color: #8492a6; font-size: 12px; margin-left: 8px">{{ city.province }}</span>
                </el-option>
              </el-select>
              <!-- 城市加载进度提示 -->
              <div v-if="cityLoading" class="city-loading-progress">
                <el-progress 
                  :percentage="cityLoadProgress" 
                  :show-text="true"
                  :stroke-width="6"
                  status="success"
                ></el-progress>
                <div class="progress-text">{{ cityLoadText }}</div>
              </div>
            </el-form-item>
            
            <el-form-item label="入住/离店日期">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="入住日期"
                end-placeholder="离店日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :shortcuts="dateShortcuts"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            
            <el-form-item label="关键词">
              <el-input 
                v-model="searchForm.queryText" 
                placeholder="酒店名称/地址" 
                @keyup.enter="searchHotels"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="searchHotels" :loading="loading" style="width: 100%">
                <el-icon><Search /></el-icon> 搜索酒店
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 筛选条件 -->
        <el-card class="filter-card">
            <template #header>
              <div class="filter-header">
                <h3>筛选条件</h3>
                <el-button type="text" @click="resetForm">清除全部</el-button>
              </div>
            </template>
            
            <div class="filter-section">
              <h4>价格区间</h4>
              <el-slider
                v-model="priceRange"
                range
                :min="0"
                :max="2000"
                :step="50"
              ></el-slider>
              <div class="price-range-display">
                <span>¥{{ priceRange[0] }}</span>
                <span>¥{{ priceRange[1] }}</span>
              </div>
            </div>
            
            <div class="filter-section">
              <h4>酒店星级</h4>
              <el-select 
                v-model="searchForm.ranks" 
                multiple
                placeholder="选择星级"
                collapse-tags
                collapse-tags-tooltip
                style="width: 100%"
              >
                <el-option label="五星级" value="5"></el-option>
                <el-option label="四星级" value="4"></el-option>
                <el-option label="三星级" value="3"></el-option>
                <el-option label="二星级" value="2"></el-option>
                <el-option label="一星级" value="1"></el-option>
              </el-select>
            </div>
            
            <div class="filter-section">
              <h4>排序方式</h4>
              <el-select 
                v-model="searchForm.sortType" 
                placeholder="选择排序方式"
                clearable
                style="width: 100%"
              >
                <el-option label="默认排序" value=""></el-option>
                <el-option label="价格升序" value="PRICE_ASC"></el-option>
                <el-option label="价格降序" value="PRICE_DESC"></el-option>
                <el-option label="星级升序" value="START_ASC"></el-option>
                <el-option label="星级降序" value="START_DESC"></el-option>
                <el-option label="距离升序" value="DISTANCE_ASC"></el-option>
                <el-option label="距离降序" value="DISTANCE_DESC"></el-option>
                <el-option label="好评降序" value="COMMENT_DESC"></el-option>
                <el-option label="好评升序" value="COMMENT_ASC"></el-option>
              </el-select>
            </div>
            
            <el-button type="primary" @click="applyFilters" class="apply-filters-btn">应用筛选</el-button>
          </el-card>
        </div>
      </div>
      
      <!-- 右侧：酒店列表区域 -->
      <div class="right-content">
          <!-- 固定在顶部的分页区域 -->
          <div v-if="searchResult.length > 0" class="list-header">
            <div class="result-count">
              找到 <span class="highlight">{{ totalCount }}</span> 家酒店
            </div>
            <div class="pagination-top">
              <el-pagination
                v-model:current-page="searchForm.pageIndex"
                :page-size="searchForm.pageSize"
                :total="totalCount"
                layout="prev, pager, next"
                @current-change="handlePageChange"
                background
                small
                hide-on-single-page
              ></el-pagination>
            </div>
          </div>
          
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="10" animated />
          </div>
          
          <div v-else-if="searchResult.length > 0" class="hotel-list">
              <el-card v-for="hotel in searchResult" :key="hotel.hotelCode" class="hotel-card">
              <div class="hotel-card-content">
                <div class="hotel-image" v-if="getHotelImage(hotel)">
                  <img :src="getHotelImage(hotel)" :alt="hotel.hotelName || hotel.name" />
                </div>
                <div class="hotel-info">
                  <div class="hotel-name-rating">
                    <h3 class="hotel-name">{{ hotel.hotelName || hotel.name }}</h3>
                    <div class="hotel-rating">
                      <el-rate
                        v-if="hotel.rank && getRankStars(hotel.rank) > 0"
                        :model-value="getRankStars(hotel.rank)"
                        disabled
                        text-color="#ff9900"
                      ></el-rate>
                      <el-rate
                        v-else-if="hotel.commentPoint"
                        :model-value="hotel.commentPoint"
                        disabled
                        text-color="#ff9900"
                      ></el-rate>
                      <span v-if="hotel.rank" class="star-label">{{ getRankName(hotel.rank) }}</span>
                    </div>
                  </div>
                  
                  <div class="hotel-tags">
                    <el-tag v-if="hotel.rank" size="small" type="success" effect="plain">{{ getRankName(hotel.rank) }}</el-tag>
                    <el-tag v-if="hotel.commentPoint" size="small" type="warning" effect="plain">{{ hotel.commentPoint }}分</el-tag>
                    <el-tag v-if="hotel.district" size="small" type="info" effect="plain">{{ hotel.district }}</el-tag>
                  </div>
                  
                  <div class="hotel-address">
                    <el-icon><Location /></el-icon>
                    <span>{{ hotel.city || hotel.cityName || '' }} {{ hotel.district ? '·' + hotel.district : '' }} {{ hotel.address || '暂无地址信息' }}</span>
                  </div>
                  
                  <div v-if="hotel.distance" class="hotel-distance">
                    <el-icon><Position /></el-icon>
                    <span>距离约 {{ formatDistance(hotel.distance) }}</span>
                  </div>
                  
                  <div v-if="getHotelAmenities(hotel) && getHotelAmenities(hotel).length > 0" class="hotel-facilities">
                    <span v-for="(facility, index) in getHotelAmenities(hotel).slice(0, 4)" :key="index" class="facility-item">
                      {{ facility }}
                    </span>
                  </div>
                </div>
                
                <div class="hotel-price-actions">
                  <div class="hotel-price" v-if="hotel.minPrice && hotel.minPrice > 0">
                    <div class="price-label">起价</div>
                    <div class="price-value">¥{{ hotel.minPrice.toFixed(2) }}</div>
                    <div class="price-night">每晚</div>
                  </div>
                  <div class="hotel-price" v-else>
                    <span class="no-price">暂无报价</span>
                  </div>
                  
                  <div class="hotel-actions">
                    <el-button @click="viewHotelDetail(hotel.hotelCode)" type="default">查看详情</el-button>
                    <el-button @click="viewRoomProducts(hotel.hotelCode)" type="primary">选择房型</el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          
          <el-empty v-else-if="hasSearched" description="未找到符合条件的酒店" class="empty-result">
            <template #image>
              <el-icon :size="60"><Search /></el-icon>
            </template>
            <template #description>
              <p>未找到符合条件的酒店</p>
              <p class="empty-suggestion">您可以尝试修改搜索条件或选择其他城市</p>
            </template>
          </el-empty>
          
          <div v-else class="welcome-container">
            <el-empty description="请输入搜索条件查询酒店">
              <template #image>
                <el-icon :size="60"><House /></el-icon>
              </template>
              <template #description>
                <p>输入目的地和日期开始您的酒店搜索</p>
              </template>
            </el-empty>
          </div>
      </div>
    </div>
    
    <el-dialog v-model="showRawData" title="原始数据" width="80%">
      <pre>{{ JSON.stringify(rawData, null, 2) }}</pre>
    </el-dialog>
    
    <div class="floating-button">
      <el-button circle @click="showRawData = true" v-if="rawData">
        <el-icon><DataAnalysis /></el-icon>
      </el-button>
    </div>
    
    <!-- 酒店详情弹窗 -->
    <el-dialog
      v-model="showHotelDetail"
      :title="selectedHotel ? selectedHotel.hotelName : '酒店详情'"
      :width="isMobile ? '100%' : '1200px'"
      :fullscreen="isMobile"
      :top="isMobile ? '0' : '5vh'"
      destroy-on-close
      :show-close="true"
      @close="closeHotelDetail"
      class="mobile-friendly-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="dialog-title">
            <el-button v-if="isMobile" @click="closeHotelDetail" class="back-button" text>
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <h3>{{ selectedHotel ? selectedHotel.hotelName : '酒店详情' }}</h3>
          </div>
          <el-button v-if="!isMobile" @click="closeHotelDetail" class="close-button" circle>
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      
      <hotel-detail-component 
        v-if="selectedHotel" 
        :hotelId="selectedHotel.hotelCode"
        @view-rooms="openRoomProducts"
      />
    </el-dialog>
    
    <!-- 房型选择弹窗 -->
    <el-dialog
      v-model="showRoomProducts"
      title="房型及产品选择"
      :width="isMobile ? '100%' : '1200px'"
      :fullscreen="isMobile"
      :top="isMobile ? '0' : '5vh'"
      destroy-on-close
      :show-close="true"
      @close="closeRoomProducts"
      class="mobile-friendly-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="dialog-title">
            <el-button v-if="isMobile" @click="closeRoomProducts" class="back-button" text>
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <h3>房型及产品选择</h3>
          </div>
          <el-button v-if="!isMobile" @click="closeRoomProducts" class="close-button" circle>
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      
      <room-products-component 
        v-if="showRoomProducts && currentHotelId" 
        :hotelId="currentHotelId"
        :check-in-date="searchForm.checkInDate"
        :check-out-date="searchForm.checkOutDate"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { searchHotels as searchHotelsApi, queryCityList } from '../api/hotelApi';
import { ElMessage } from 'element-plus';
import { DataAnalysis, Search, Location, Position, House, ArrowLeft, Close } from '@element-plus/icons-vue';
import HotelDetailComponent from '../components/HotelDetailComponent.vue';
import RoomProductsComponent from '../components/RoomProductsComponent.vue';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const searchResult = ref([]);
const totalCount = ref(0);
const rawData = ref(null);
const showRawData = ref(false);
const hasSearched = ref(false);

// 城市列表相关
const cityList = ref([]);
const cityLoading = ref(false);
const allCities = ref([]); // 存储所有城市数据
const cityLoadProgress = ref(0); // 城市加载进度
const cityLoadText = ref('正在加载城市列表...'); // 加载状态文本

// 弹窗相关状态
const showHotelDetail = ref(false);
const showRoomProducts = ref(false);
const selectedHotel = ref(null);
const currentHotelId = ref(null);

// 检测是否为移动设备
const isMobile = computed(() => {
  return window.innerWidth <= 768;
});

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener('resize', () => {
    // 窗口大小变化时会自动重新计算isMobile
  });
});

// 获取当前日期和明天日期
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 日期范围
const dateRange = ref([formatDate(today), formatDate(tomorrow)]);

// 价格范围
const priceRange = ref([0, 1000]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天至明天',
    value: () => {
      const start = new Date();
      const end = new Date();
      end.setDate(start.getDate() + 1);
      return [start, end];
    },
  },
  {
    text: '本周末',
    value: () => {
      const start = new Date();
      const end = new Date();
      const day = start.getDay();
      start.setDate(start.getDate() + (day === 0 ? 6 : 6 - day));
      end.setDate(start.getDate() + 1);
      return [start, end];
    },
  },
  {
    text: '下周末',
    value: () => {
      const start = new Date();
      const end = new Date();
      const day = start.getDay();
      start.setDate(start.getDate() + (day === 0 ? 13 : 13 - day));
      end.setDate(start.getDate() + 1);
      return [start, end];
    },
  }
];

const searchForm = reactive({
  cityCode: '',
  checkInDate: formatDate(today),
  checkOutDate: formatDate(tomorrow),
  queryText: '',    // 关键词搜索
  ranks: [],        // 星级筛选（S1-S5, A1-A5）
  minPrice: null,
  maxPrice: null,
  sortType: '',     // 排序类型（PRICE_ASC, PRICE_DESC等）
  pageIndex: 1,
  pageSize: 10
});

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    searchForm.checkInDate = newVal[0];
    searchForm.checkOutDate = newVal[1];
  }
});

// 获取酒店图片
const getHotelImage = (hotel) => {
  if (hotel.images && hotel.images.length > 0) {
    return hotel.images[0].url;
  }
  return '';
};

// 获取酒店设施
const getHotelAmenities = (hotel) => {
  if (hotel.hotelAmenities && Array.isArray(hotel.hotelAmenities)) {
    return hotel.hotelAmenities;
  }
  return [];
};

// 星级等级名称映射（rank格式：S1-S5正式星级，A1-A5准星级）
const getRankName = (rank) => {
  // 统一星级显示，不区分准星级和正式星级
  const rankMap = {
    'S1': '一星级',
    'S2': '二星级',
    'S3': '三星级',
    'S4': '四星级',
    'S5': '五星级',
    'A1': '一星级',  // 准星级也显示为统一的星级
    'A2': '二星级',
    'A3': '三星级',
    'A4': '四星级',
    'A5': '五星级'
  };
  return rankMap[rank] || rank;
};

// 获取星级对应的数字（用于显示星星）
const getRankStars = (rank) => {
  // S1-S5和A1-A5都对应1-5星
  const match = rank?.match(/[SA](\d)/);
  if (match) {
    return parseInt(match[1]);
  }
  return 0;
};

// 格式化距离
const formatDistance = (distance) => {
  if (distance < 1000) {
    return `${distance}米`;
  } else {
    return `${(distance / 1000).toFixed(1)}公里`;
  }
};

// 获取城市列表（分页获取所有数据）
const fetchCityList = async () => {
  cityLoading.value = true;
  cityLoadProgress.value = 0;
  cityLoadText.value = '正在加载城市列表...';
  
  const allCitiesData = [];
  let currentPage = 1;
  let hasMoreData = true;
  const pageSize = 100; // 每页最大100条
  const maxPages = 20; // 最大页数限制
  
  try {
    console.log('开始分页获取城市列表...');
    
    // 循环获取所有页面的数据
    let consecutiveFailures = 0; // 连续失败次数
    const maxConsecutiveFailures = 3; // 最大连续失败次数
    
    while (hasMoreData) {
      // 更新进度文本
      cityLoadText.value = `正在获取第 ${currentPage} 页城市数据...`;
      console.log(`正在获取第 ${currentPage} 页城市数据...`);
      
      try {
        const response = await queryCityList({ page: currentPage, row: pageSize });
        
        if (response.data) {
          let pageData = [];
          
          // 适配不同的响应格式
          if (Array.isArray(response.data)) {
            pageData = response.data;
          } else if (response.data.list || response.data.cities) {
            pageData = response.data.list || response.data.cities || [];
          }
          
          // 如果当前页没有数据，说明已经获取完所有数据
          if (pageData.length === 0) {
            hasMoreData = false;
            console.log(`第 ${currentPage} 页无数据，停止获取`);
          } else {
            // 合并数据
            allCitiesData.push(...pageData);
            console.log(`第 ${currentPage} 页获取到 ${pageData.length} 个城市，累计 ${allCitiesData.length} 个`);
            
            // 重置连续失败计数
            consecutiveFailures = 0;
            
            // 更新进度（基于页数）
            const progress = Math.min((currentPage / maxPages) * 100, 95); // 最多显示95%，留5%给完成状态
            cityLoadProgress.value = Math.round(progress);
            
            // 如果当前页数据少于pageSize，说明这是最后一页
            if (pageData.length < pageSize) {
              hasMoreData = false;
              console.log(`第 ${currentPage} 页数据不足 ${pageSize} 条，已获取完所有数据`);
            } else {
              currentPage++;
            }
          }
        } else {
          console.error(`第 ${currentPage} 页获取失败:`, response.msg || response.message || '未知错误');
          consecutiveFailures++;
          
          // 如果连续失败次数过多，停止获取
          if (consecutiveFailures >= maxConsecutiveFailures) {
            console.warn(`连续 ${maxConsecutiveFailures} 页获取失败，停止获取`);
            hasMoreData = false;
          } else {
            // 跳过当前页，继续下一页
            currentPage++;
            console.log(`跳过第 ${currentPage - 1} 页，继续获取第 ${currentPage} 页`);
          }
        }
      } catch (pageError) {
        console.error(`第 ${currentPage} 页请求异常:`, pageError);
        consecutiveFailures++;
        
        // 如果连续失败次数过多，停止获取
        if (consecutiveFailures >= maxConsecutiveFailures) {
          console.warn(`连续 ${maxConsecutiveFailures} 页请求异常，停止获取`);
          hasMoreData = false;
        } else {
          // 跳过当前页，继续下一页
          currentPage++;
          console.log(`跳过第 ${currentPage - 1} 页，继续获取第 ${currentPage} 页`);
        }
      }
      
      // 防止无限循环，最多获取20页（2000条数据）
      if (currentPage > maxPages) {
        console.warn(`已达到最大页数限制（${maxPages}页），停止获取`);
        hasMoreData = false;
      }
    }
    
    // 完成加载
    cityLoadProgress.value = 100;
    cityLoadText.value = '城市列表加载完成';
    
    // 设置城市数据
    allCities.value = allCitiesData;
    cityList.value = allCitiesData;
    
    if (cityList.value.length === 0) {
      ElMessage.warning('未获取到城市列表');
    } else {
      console.log(`成功加载所有城市数据，共 ${cityList.value.length} 个城市`);
      ElMessage.success(`成功加载 ${cityList.value.length} 个城市`);
      
      // 默认选择第一个城市并查询酒店
      if (cityList.value.length > 0 && !searchForm.cityCode) {
        const firstCity = cityList.value[0];
        searchForm.cityCode = firstCity.cityCode;
        
        // 自动触发搜索
        setTimeout(() => {
          searchHotels();
        }, 300);
      }
    }
  } catch (error) {
    console.error('获取城市列表出错:', error);
    ElMessage.error('获取城市列表出错，请稍后重试');
    cityList.value = [];
    cityLoadText.value = '加载失败，请重试';
  } finally {
    // 延迟隐藏进度条，让用户看到完成状态
    setTimeout(() => {
      cityLoading.value = false;
    }, 1000);
  }
};

// 处理城市选择
const handleCityChange = (cityCode) => {
  if (cityCode) {
    const selectedCity = cityList.value.find(city => city.cityCode === cityCode);
    if (selectedCity) {
      console.log('选择城市:', selectedCity);
    }
  }
};

// 应用筛选条件
const applyFilters = () => {
  searchForm.minPrice = priceRange.value[0] || null;
  searchForm.maxPrice = priceRange.value[1] || null;
  searchForm.pageIndex = 1;
  searchHotels();
};

const searchHotels = async () => {
  if (!searchForm.cityCode) {
    ElMessage.warning('请选择城市');
    return;
  }
  
  if (!searchForm.checkInDate || !searchForm.checkOutDate) {
    ElMessage.warning('请选择入住和离店日期');
    return;
  }
  
  loading.value = true;
  hasSearched.value = true;
  
  try {
    // 构建基础参数
    const params = {
      cityCode: searchForm.cityCode,
      checkInDate: searchForm.checkInDate,
      checkOutDate: searchForm.checkOutDate,
      pageIndex: searchForm.pageIndex,
      pageSize: searchForm.pageSize
    };
    
    // 添加关键词（如果有）
    if (searchForm.queryText) {
      params.keyword = searchForm.queryText;
    }
    
    // 转换星级：将简化的星级值（1-5）转换为A级和S级的组合
    // 例如：["1", "3"] -> ["A1", "S1", "A3", "S3"]
    let convertedRanks = [];
    if (searchForm.ranks && searchForm.ranks.length > 0) {
      searchForm.ranks.forEach(rank => {
        convertedRanks.push(`A${rank}`);  // 准星级
        convertedRanks.push(`S${rank}`);  // 正式星级
      });
    }
    
    // 构建 condition 对象（将筛选条件放入condition）
    const hasMinPrice = searchForm.minPrice !== null && searchForm.minPrice > 0;
    const hasMaxPrice = searchForm.maxPrice !== null && searchForm.maxPrice > 0;
    const hasRanks = convertedRanks.length > 0;
    const hasSortType = searchForm.sortType;
    
    // 只有当有任何筛选条件时才添加
    if (hasMinPrice || hasMaxPrice || hasRanks || hasSortType) {
      params.minPrice = searchForm.minPrice;
      params.maxPrice = searchForm.maxPrice;
      params.ranks = convertedRanks;  // 使用转换后的星级数组
      params.sortType = searchForm.sortType;
    }
    
    const response = await searchHotelsApi(params);
    rawData.value = response;
    
    console.log('API响应数据:', response);
    
    if (response.data) {
      // 适配新API的响应数据格式
      // 注意：根据实际API文档调整数据字段
      if (Array.isArray(response.data)) {
        // 如果data直接是数组
        searchResult.value = response.data;
        totalCount.value = response.data.length;
      } else if (response.data.hotelList || response.data.list || response.data.hotels) {
        // 如果data是对象，包含列表字段
        searchResult.value = response.data.hotelList || response.data.list || response.data.hotels || [];
        totalCount.value = response.data.count || response.data.total || response.data.totalCount || 0;
      } else {
        // 其他情况
        searchResult.value = [];
        totalCount.value = 0;
      }
      
      if (searchResult.value.length === 0) {
        ElMessage.info('未找到符合条件的酒店');
      } else {
        ElMessage.success(`找到 ${totalCount.value} 家酒店`);
      }
    } else {
      ElMessage.error(`搜索失败: ${response.msg || response.message || '未知错误'}`);
      searchResult.value = [];
      totalCount.value = 0;
    }
  } catch (error) {
    console.error('搜索酒店出错:', error);
    ElMessage.error('搜索酒店出错，请稍后重试');
    searchResult.value = [];
    totalCount.value = 0;
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  searchForm.cityCode = '';
  searchForm.checkInDate = formatDate(today);
  searchForm.checkOutDate = formatDate(tomorrow);
  searchForm.queryText = '';
  searchForm.ranks = [];
  searchForm.minPrice = null;
  searchForm.maxPrice = null;
  searchForm.sortType = '';
  searchForm.pageIndex = 1;
  searchForm.pageSize = 10;
  dateRange.value = [formatDate(today), formatDate(tomorrow)];
  priceRange.value = [0, 1000];
};

const handlePageChange = (page) => {
  searchForm.pageIndex = page;
  searchHotels();
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

const handleSizeChange = (size) => {
  searchForm.pageSize = size;
  searchForm.pageIndex = 1;
  searchHotels();
};

const viewHotelDetail = (hotelId) => {
  const hotel = searchResult.value.find(h => h.hotelCode == hotelId);
  if (hotel) {
    selectedHotel.value = hotel;
    showHotelDetail.value = true;
    // 更新URL，但不导航
    window.history.pushState({}, '', `/hotel-detail/${hotelId}`);
  }
};

const viewRoomProducts = (hotelId) => {
  currentHotelId.value = hotelId;
  showRoomProducts.value = true;
  // 更新URL，但不导航
  window.history.pushState({}, '', `/room-products/${hotelId}`);
};

// 关闭酒店详情弹窗
const closeHotelDetail = () => {
  showHotelDetail.value = false;
  selectedHotel.value = null;
  // 恢复URL
  window.history.pushState({}, '', '/hotel-search');
};

// 关闭房型选择弹窗
const closeRoomProducts = () => {
  showRoomProducts.value = false;
  // 如果是从酒店详情打开的，则恢复到酒店详情URL
  if (selectedHotel.value) {
    window.history.pushState({}, '', `/hotel-detail/${selectedHotel.value.hotelCode}`);
  } else {
    // 否则恢复到搜索页
    window.history.pushState({}, '', '/hotel-search');
  }
};

// 从酒店详情打开房型选择
const openRoomProducts = (hotelId) => {
  currentHotelId.value = hotelId;
  showRoomProducts.value = true;
  // 更新URL
  window.history.pushState({}, '', `/room-products/${hotelId}`);
};

// 监听路由变化，处理弹窗显示
const handleRouteChange = () => {
  const currentRoute = route.path;
  const params = route.params;
  
  // 处理酒店详情弹窗
  if (currentRoute.includes('/hotel-detail/') && params.hotelId) {
    const hotelId = params.hotelId;
    // 如果已经有搜索结果，从中查找
    if (searchResult.value.length > 0) {
      const hotel = searchResult.value.find(h => h.hotelCode == hotelId);
      if (hotel) {
        selectedHotel.value = hotel;
        showHotelDetail.value = true;
        return;
      }
    }
    
    // 如果没有找到，直接设置hotelCode
    selectedHotel.value = { hotelCode: hotelId };
    showHotelDetail.value = true;
  } 
  // 处理房型选择弹窗
  else if (currentRoute.includes('/room-products/') && params.hotelId) {
    const hotelId = params.hotelId;
    currentHotelId.value = hotelId;
    showRoomProducts.value = true;
  }
};

// 页面加载时获取城市列表并处理路由
onMounted(() => {
  fetchCityList(); // 先获取城市列表
  handleRouteChange();
});

// 监听路由变化
watch(() => route.path, () => {
  handleRouteChange();
});
</script>

<style scoped>
.hotel-search {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

/* 左右布局 */
.search-layout {
  display: flex;
  height: 100%;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 左侧边栏 */
.left-sidebar {
  width: 300px;
  flex-shrink: 0;
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 12px 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  flex-shrink: 0;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 左侧内容滚动区域 */
.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.sidebar-content::-webkit-scrollbar {
  width: 4px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 2px;
}

/* 查询卡片 */
.query-card {
  margin-bottom: 8px;
}

.query-card :deep(.el-card__header) {
  padding: 8px 12px;
  background-color: #f5f7fa;
}

.query-card :deep(.el-card__body) {
  padding: 12px;
}

.query-card h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.query-card :deep(.el-form-item) {
  margin-bottom: 10px;
}

.query-card :deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.query-card :deep(.el-form-item__label) {
  padding: 0;
  margin-bottom: 4px;
  font-size: 12px;
  line-height: 1.4;
}

.query-card :deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
  font-size: 13px;
}

.query-card :deep(.el-select .el-input__inner) {
  height: 32px;
}

.query-card :deep(.el-date-editor) {
  height: 32px;
}

.query-card :deep(.el-date-editor .el-input__inner) {
  height: 32px;
  font-size: 12px;
}

.query-card :deep(.el-button) {
  height: 32px;
  padding: 8px 15px;
  font-size: 13px;
}

/* 城市加载进度样式 */
.city-loading-progress {
  margin-top: 8px;
  padding: 8px 0;
}

.city-loading-progress :deep(.el-progress) {
  margin-bottom: 4px;
}

.city-loading-progress :deep(.el-progress__text) {
  font-size: 11px;
  color: #606266;
}

.progress-text {
  font-size: 11px;
  color: #909399;
  text-align: center;
  margin-top: 4px;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: 8px;
}

.filter-card :deep(.el-card__header) {
  padding: 8px 12px;
  background-color: #f5f7fa;
}

.filter-card :deep(.el-card__body) {
  padding: 12px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.filter-section {
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.filter-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.filter-section h4 {
  margin: 0 0 6px 0;
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.price-range-display {
  display: flex;
  justify-content: space-between;
  margin-top: 6px;
  color: #606266;
  font-size: 11px;
}

.filter-card :deep(.el-select) {
  font-size: 12px;
}

.filter-card :deep(.el-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
}

.filter-card :deep(.el-slider) {
  margin: 8px 0;
}

.filter-card :deep(.el-slider__runway) {
  height: 4px;
}

.filter-card :deep(.el-slider__button) {
  width: 12px;
  height: 12px;
}

.apply-filters-btn {
  width: 100%;
  margin-top: 8px;
  height: 32px;
  padding: 8px 15px;
  font-size: 13px;
}

/* 右侧内容区域 */
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 酒店列表 */
.hotel-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.hotel-list::-webkit-scrollbar {
  width: 6px;
}

.hotel-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.hotel-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.hotel-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.loading-container, .welcome-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.list-header {
  padding: 8px 12px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.result-count {
  font-size: 14px;
  font-weight: 500;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.pagination-top :deep(.el-pagination) {
  padding: 0;
}

.pagination-top :deep(.el-pager li) {
  min-width: 28px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
}

.pagination-top :deep(.btn-prev),
.pagination-top :deep(.btn-next) {
  padding: 0 8px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
}

.hotel-card {
  margin-bottom: 8px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.hotel-card :deep(.el-card__body) {
  padding: 12px;
}

.hotel-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.hotel-card-content {
  display: flex;
  flex-wrap: wrap;
}

.hotel-image {
  width: 160px;
  height: 110px;
  overflow: hidden;
  border-radius: 4px;
  margin-right: 12px;
  flex-shrink: 0;
}

.hotel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.hotel-card:hover .hotel-image img {
  transform: scale(1.05);
}

.hotel-info {
  flex: 1;
  min-width: 280px;
}

.hotel-name-rating {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 6px;
}

.hotel-name {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  line-height: 1.4;
}

.hotel-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.hotel-rating :deep(.el-rate) {
  height: 16px;
}

.hotel-rating :deep(.el-rate__icon) {
  font-size: 14px;
  margin-right: 2px;
}

.star-label {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

.hotel-tags {
  margin-bottom: 6px;
}

.hotel-tags .el-tag {
  margin-right: 4px;
  height: 20px;
  line-height: 18px;
  font-size: 11px;
  padding: 0 6px;
}

.hotel-address, .hotel-distance {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
}

.hotel-address .el-icon, .hotel-distance .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.hotel-facilities {
  margin-top: 6px;
  display: flex;
  flex-wrap: wrap;
}

.facility-item {
  background-color: #f5f7fa;
  color: #606266;
  padding: 2px 6px;
  margin-right: 4px;
  margin-bottom: 4px;
  border-radius: 3px;
  font-size: 11px;
}

.hotel-price-actions {
  width: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
  padding-left: 12px;
  flex-shrink: 0;
}

.hotel-price {
  text-align: right;
  margin-bottom: 10px;
}

.price-label {
  font-size: 11px;
  color: #909399;
}

.price-value {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
  line-height: 1.2;
}

.price-night {
  font-size: 11px;
  color: #909399;
}

.no-price {
  color: #909399;
  font-size: 13px;
}

.hotel-actions {
  display: flex;
  flex-direction: row;
  gap: 8px;
  width: 100%;
}

.hotel-actions .el-button {
  margin-left: 0 !important;
  padding: 6px 12px;
  font-size: 13px;
  flex: 1;
}


.empty-result {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.empty-suggestion {
  font-size: 13px;
  color: #909399;
  margin-top: 5px;
}

.floating-button {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 100;
}

.floating-button .el-button {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 移动端友好的弹窗样式 */
.mobile-friendly-dialog {
  margin: 0 !important;
}

.mobile-friendly-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
}

.mobile-friendly-dialog :deep(.el-dialog__body) {
  padding: 12px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.mobile-friendly-dialog :deep(.el-dialog__headerbtn) {
  display: none;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.dialog-title {
  display: flex;
  align-items: center;
}

.dialog-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.back-button {
  margin-right: 8px;
  font-size: 18px;
}

.close-button {
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .hotel-search {
    padding: 10px;
  }
  
  .search-layout {
    flex-direction: column;
  }
  
  .left-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
    max-height: 40vh;
  }
  
  .hotel-card-content {
    flex-direction: column;
  }
  
  .hotel-image {
    width: 100%;
    height: 180px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .hotel-price-actions {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding-left: 0;
    margin-top: 10px;
  }
  
  .hotel-actions {
    flex-direction: row;
    width: auto;
  }
}
</style>